package com.zhuqi.netty.handler;

import com.zhuqi.proto.LogOutMessageProto;
import com.zhuqi.util.WebsocketUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.Session;
import java.nio.charset.StandardCharsets;

/**
 * <p>登出处理器</p>
 * @author zhuqi
 * @since 2023/3/10 14:17
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class LogOutHandler extends SimpleChannelInboundHandler<LogOutMessageProto.LogOutMessageResponse> {

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, LogOutMessageProto.LogOutMessageResponse msg) {
		boolean flag = msg.getFlag();
		String content = new String(msg.getContent().getBytes(), StandardCharsets.UTF_8);
		String name = new String(msg.getName().getBytes(), StandardCharsets.UTF_8);
		log.info("登出状态:{} 消息：{}", flag, content);
		Session userSession = WebsocketUtil.getUserSession(name);
		if (userSession != null) {
			WebsocketUtil.sendMessage(userSession, content);
			WebsocketUtil.updateLoggingStatus(userSession, Boolean.FALSE);
		}

	}
}
